package http

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"mall-portalv2/global"
	"mall-portalv2/internal/model"
	"mall-portalv2/internal/server/ctx"
	"mall-portalv2/library/common"
	"net/http"
)

func OrderListHandlerFunc(c *gin.Context) {
	app := ctx.Gin{C: c}

	pageNum := common.Str2Int(c.Query("pageNum"))
	pageSize := common.Str2Int(c.Query("pageSize"))
	status := common.Str2Int(c.Query("status"))

	uidStr, isUid := c.Get("uid")
	if !isUid {
		global.Log.Error("uid不存在")
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, nil)
		return
	}
	UID := common.Str2Int64(fmt.Sprintf("%d", uidStr))

	// 订单状态：-1->全部；0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->售后
	// TODO: 如果是涉及到售后单的，单独处理
	if status == 5 {
		result, err := svc.QueryViewOmsOrderReturnApplyList(c, UID, pageNum, pageSize)
		if err != nil {
			global.Log.Error("mysql query error", zap.Error(err))
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}
		orderResultList := []model.ViewOmsOrderReturnApplyList{}
		reBt, _ := json.Marshal(result)
		json.Unmarshal(reBt, &orderResultList)

		var ids = []int64{}
		for _, order := range orderResultList {
			ids = append(ids, order.ID)
		}

		//	查询每一单下的商品详情
		orderItemResult, err := svc.QueryOmsOrderItemWhereOrderIds(c, ids)
		if err != nil {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}

		for i, order := range result {
			for _, product := range orderItemResult {
				if product.OrderId == order.ID {
					orderResultList[i].OrderItemList = append(orderResultList[i].OrderItemList, product)
				} else {
					continue
				}
			}
		}
		resultCount, err := svc.QueryViewOmsOrderReturnApplyListCount(c, UID)
		if err != nil {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}
		app.Response(http.StatusOK, ctx.OK, gin.H{
			"list":      orderResultList,
			"pageNum":   pageNum,
			"pageSize":  pageSize,
			"total":     resultCount,
			"totalPage": resultCount / int64(pageSize),
		})
		return
	} else {
		result, err := svc.QueryOmsOrderList(c, UID, status, pageNum, pageSize)
		if err != nil {
			global.Log.Error("mysql query error", zap.Error(err))
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}

		orderResultList := []model.OrderList{}

		reBt, _ := json.Marshal(result)
		json.Unmarshal(reBt, &orderResultList)

		var ids = []int64{}
		for _, order := range orderResultList {
			ids = append(ids, order.ID)
		}

		//	查询每一单下的商品详情
		orderItemResult, err := svc.QueryOmsItemAndProductWhereOrderIds(c, ids)
		if err != nil {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}

		for i, order := range result {
			for _, product := range orderItemResult {
				if product.OrderId == order.ID {
					orderResultList[i].OrderItemList = append(orderResultList[i].OrderItemList, product)
				} else {
					continue
				}
			}
		}

		resultCount, err := svc.QueryOmsOrderListCount(c, UID, status, 0)
		if err != nil {
			app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
			return
		}
		app.Response(http.StatusOK, ctx.OK, gin.H{
			"list":      orderResultList,
			"pageNum":   pageNum,
			"pageSize":  pageSize,
			"total":     resultCount,
			"totalPage": resultCount / int64(pageSize),
		})
		return
	}
}

func OrderListReadHandlerFunc(c *gin.Context) {
	app := ctx.Gin{C: c}

	type RequestBody struct {
		Ids []int64 `json:"ids"`
	}

	request := RequestBody{}
	if err := common.BindAndCheck(c, &request); err != nil {
		global.Log.Error("请求参数不正确", zap.Error(err))
		app.Response(http.StatusBadRequest, ctx.StatusBadRequest, err)
		return
	}

	global.Log.Info("映射完成", zap.Any("data", request))

	uidStr, isUid := c.Get("uid")
	if !isUid {
		global.Log.Error("uid不存在")
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, nil)
		return
	}
	UID := common.Str2Int64(fmt.Sprintf("%d", uidStr))

	// 订单状态：-1->全部；0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭
	// TODO: 批量标记订单为已读

	updates := make(map[string]interface{})
	updates["member_com"] = 1

	if err := svc.UpdateOrderWhereIds(c, request.Ids, updates, UID); err != nil {
		global.Log.Error("更新mysql出错")
		app.Response(http.StatusInternalServerError, ctx.StatusInternalServerError, err)
		return
	}

	app.Response(http.StatusOK, ctx.OK, nil)
}

// DeleteSlice3 删除指定元素。
//func DeleteSlice3(a []model.OrderList, elem model.OrderList) []int {
//	j := 0
//	for _, v := range a {
//		if v.Id != elem.Id {
//			a[j] = v
//			j++
//		}
//	}
//	return a[:j]
//}
